package com.unbook.controller;

import com.unbook.entity.ResponseVo;
import com.unbook.enums.EVerifyState;
import com.unbook.service.IVerifyService;
import com.unbook.utils.VerifyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@RestController
@RequestMapping("verify")
public class VerifyController {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    IVerifyService verifyService;

    /**
     * 生成验证码的接口
     *
     * @param request  Request对象
     * @throws Exception
     */
    @PostMapping("/getcode")
    public ResponseVo<String> getCode(HttpServletRequest request) {
        try {
            String png_base64 = verifyService.getCode(request.getSession().getId());
            return ResponseVo.success(png_base64);
        } catch (IOException e) {
            return ResponseVo.error("验证码图片生成失败");
        }
    }

    /**
     * 业务接口包含了验证码的验证
     *
     * @param code    前端传入的验证码
     * @param request Request对象
     * @return
     */
    @GetMapping("/checkcode")
    public ResponseVo<String> checkCode(String code, HttpServletRequest request) {
        EVerifyState state = verifyService.checkCode(request.getSession().getId(), code);
        return ResponseVo.custom(state.getCode(), state.getDesc());
    }
}
